package mysql

import "common/models"

func (m Mysql) UserCheckUsername(val string) (exist bool, info *models.UserInfo, err error) {
	var count int64
	exist = false
	err = m.Db.Table("user_info").Where("username =  ?", val).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = m.Db.Table("user_info").Where("username =  ?", val).First(&info).Error
	}
	return
}
func (m Mysql) UserCheckUserID(val string) (exist bool, info *models.UserInfo, err error) {
	var count int64
	exist = false
	err = m.Db.Table("user_info").Where("user_id =  ?", val).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = m.Db.Table("user_info").Where("user_id =  ?", val).First(&info).Error
	}
	return
}
func (m Mysql) UserCheckId(val string) (exist bool, info *models.UserInfo, err error) {
	var count int64
	exist = false
	err = m.Db.Table("user_info").Where("id =  ?", val).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = m.Db.Table("user_info").Where("id =  ?", val).First(&info).Error
	}
	return
}
func (m Mysql) UserCheckNickName(val string) (exist bool, info *models.UserInfo, err error) {
	var count int64
	exist = false
	err = m.Db.Table("user_info").Where("nick_name like ?", LikeType+val+LikeType).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = m.Db.Table("user_info").Where("nick_name like ?", LikeType+val+LikeType).First(&info).Error
	}
	return
}
func (m Mysql) UserAdd(val *models.UserInfo) (err error) {
	err = m.Db.Table("user_info").Create(&val).Error
	return
}
func (m Mysql) UserUpdateById(val *models.UserInfo) (err error) {
	err = m.Db.Debug().Table("user_info").Where("id = ?", val.ID).Updates(&val).Error
	return
}
func (m Mysql) UserSaveById(val *models.UserInfo) (err error) {
	err = m.Db.Debug().Table("user_info").Save(&val).Error
	return
}
func (m Mysql) UserDeleteById(val string) (err error) {
	err = m.Db.Table("user_info").Unscoped().Where("id = ?", val).Error
	return
}
func (m Mysql) UserSearchLikeNickName(val string, page, size int) (res []*models.UserInfo, total int64, err error) {
	err = m.Db.Table("user_info").Where("nick_name like ?", LikeType+val+LikeType).Offset((page - 1) * size).Limit(size).Find(&res).Count(&total).Error
	return
}
func (m Mysql) UserSearchLikeUsername(val string, page, size int) (res []*models.UserInfo, total int64, err error) {
	err = m.Db.Table("user_info").Where("username like ?", LikeType+val+LikeType).Offset((page - 1) * size).Limit(size).Find(&res).Count(&total).Error
	return
}
